package com.lv.common.utils

import okhttp3.Interceptor
import okhttp3.Response
import java.util.concurrent.TimeUnit

/**
 * 作者： ygx
 * 创建日期：2022/8/3 10:50 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 用于调试开发期间，替换baseHost的拦截器
 */

class TimeOutInterceptor : Interceptor {
    private val CONNECT_TIMEOUT = "CONNECT_TIMEOUT"
    private val READ_TIMEOUT = "READ_TIMEOUT"
    private val WRITE_TIMEOUT = "WRITE_TIMEOUT"
    override fun intercept(chain: Interceptor.Chain): Response {
        val originRequest = chain.request()
        var connectTimeout = chain.connectTimeoutMillis()
        var readTimeout = chain.readTimeoutMillis()
        var writeTimeout = chain.writeTimeoutMillis()

        val connectNew: String = originRequest.header(CONNECT_TIMEOUT) ?: ""
        val readNew: String = originRequest.header(READ_TIMEOUT) ?: ""
        val writeNew: String = originRequest.header(WRITE_TIMEOUT) ?: ""

        if (connectNew.isNotEmpty()) {
            connectTimeout = connectNew.toInt()
        }
        if (readNew.isNotEmpty()) {
            readTimeout = readNew.toInt()
        }
        if (writeNew.isNotEmpty()) {
            writeTimeout = writeNew.toInt()
        }
        return chain
            .withConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
            .withReadTimeout(readTimeout, TimeUnit.MILLISECONDS)
            .withWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS)
            .proceed(originRequest)
    }

}